﻿using LiveCharts;
using LiveCharts.Wpf;
using log4net;
using Sunny.UI;
using System.Diagnostics.CodeAnalysis;
using Excel = Microsoft.Office.Interop.Excel;

namespace JFBG

{
    public partial class Page4 : UIPage
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Page4));
        //X轴值数量初始值
        private long xCount = 1000;
        //X轴值最大计数值
        private long xTimes = 0;

        private long yCount = 0;
        //传感器选择位置
        private int sensorIndex = 0;

        private string waveFilePath = "D:\\聚芯光纤\\";

        private string waveFileName = "导出数据";

        private string waveFileNameDate = "";

        [DisallowNull]
        private Excel.Application excelApp;

        [DisallowNull]
        private Excel._Workbook workbook;

        private List<SensorDeviceData> sensorDeviceDataList = new List<SensorDeviceData>();

        private List<SensorEntity> sensorEntityList = new List<SensorEntity>();

        private Random R = new Random();//为了给Y值提供随机值


        public Page4()
        {
            InitializeComponent();
            InitChartConfig();
            #region  多Y轴曲线
            //将自定义类型MeasureModel映射到曲线坐标点
            var mapper = LiveCharts.Configurations.Mappers.Xy<DateTimePoint>()
              .X(model => model.Time)    //使用Time.作为X轴的标签
              .Y(model => model.Value);  //使用Value 作为Y轴的值
            //全局保存映射器
            Charting.For<DateTimePoint>(mapper);
            #endregion

            try
            {
                var sql = @"select * from sensor_table";
                var dt = MainForm.db.SelectDataTable(sql);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var row = dt.Rows[i];
                    var sensorEntity = new SensorEntity()
                    {
                        ID = (int)row["ID"],
                        SensorName = row["SensorName"].ToString(),
                        SensorType = (int)row["SensorType"],
                        ChannelIndex = (int)row["ChannelIndex"],
                        SensorIndex = (int)row["SensorIndex"],
                        WaveCount = (int)row["WaveCount"],
                        Expression = row["Expression"].ToString(),
                        Description = row["Description"].ToString(),
                        Param1 = row["Param1"].ToString(),
                        Param2 = row["Param2"].ToString(),
                        Param3 = row["Param3"].ToString(),
                        Param4 = row["Param4"].ToString(),
                        Param5 = row["Param5"].ToString(),
                        Param6 = row["Param6"].ToString(),
                        Param7 = row["Param7"].ToString(),
                        Param8 = row["Param8"].ToString(),
                        Param9 = row["Param9"].ToString(),
                        Param10 = row["Param10"].ToString(),
                        Param11 = row["Param11"].ToString(),
                        Param12 = row["Param12"].ToString(),
                        Param13 = row["Param13"].ToString(),
                        Param14 = row["Param14"].ToString(),
                        Param15 = row["Param15"].ToString(),
                        Param16 = row["Param16"].ToString()
                    };
                    this.cbWaveSensorSellect.Items.Add(sensorEntity.SensorName);
                    sensorEntityList.Add(sensorEntity);
                }

                if (sensorEntityList.Count > 0)
                {
                    this.cbWaveSensorSellect.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private ChartValues<DateTimePoint> InitChartValuesEmptyData()
        {
            ChartValues<DateTimePoint> chartValues = new ChartValues<DateTimePoint>();
            return chartValues;
        }

        private ChartValues<DateTimePoint> InitChartValuesData()
        {
            long timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
            string datetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)timestamp).ToLocalTime().ToString("HH:mm:ss");
            ChartValues<DateTimePoint> chartValues = new ChartValues<DateTimePoint>();
            for (long i = 1; i <= this.xCount; i++)
            {
                chartValues.Add(new DateTimePoint(timestamp + i * 1000, 1 + R.NextDouble()));
            }
            return chartValues;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            sensorIndex = cbWaveSensorSellect.SelectedIndex;
            DateTime startTime = startDatetime.Value;
            DateTime endTime = endDatetime.Value;
            QuerySqlData(sensorIndex, startTime, endTime);
        }
        public void QuerySqlData(int sensorIndex, DateTime startTime, DateTime endTime)
        {
            try
            {
                sensorDeviceDataList.Clear();
                SensorEntity sensorEntity = sensorEntityList.Get(sensorIndex);
                var sql = @"select * from sensor_device_data where 1=1 ";
                if (sensorEntity != null)
                {
                    sql = sql + @" and sensor_id=" + sensorEntity.ID;
                }
                //sql = sql + @" and collect_time > " + startTime.DateTimeString() + @" and collect_time < " + endTime.DateTimeString() + @" limit 10000";
                sql = sql + @" and collect_time > " + ToUnixTimestampMilliseconds(startTime) + @" and collect_time < " + ToUnixTimestampMilliseconds(endTime) + @" order by collect_time limit " + this.xCount + @";";
                var dt = MainForm.db.SelectDataTable(sql);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var row = dt.Rows[i];
                    var sensorDeviceData = new SensorDeviceData()
                    {
                        id = (long)row["id"],
                        collect_time = (long)row["collect_time"],
                        channel_id = (int)row["channel_id"],
                        sensor_type = (int)row["sensor_type"],
                        sensor_count = (int)row["sensor_count"],
                        sensor_index = (int)row["sensor_index"],
                        sensor_id = (int)row["sensor_id"],
                        sensor_name = (string)row["sensor_name"],
                        count_value1 = row["count_value1"] != DBNull.Value ? Convert.ToDouble(row["count_value1"]) : 0.0,//(double)row["count_value1"],
                        count_value2 = row["count_value2"] != DBNull.Value ? Convert.ToDouble(row["count_value2"]) : 0.0,//(double)row["count_value2"],
                        count_value3 = row["count_value3"] != DBNull.Value ? Convert.ToDouble(row["count_value3"]) : 0.0,//(double)row["count_value3"],
                    };
                    sensorDeviceDataList.Add(sensorDeviceData);
                }
                if (sensorDeviceDataList.Count > 0)
                {
                    ShowSensorChartData(sensorEntity.SensorType, sensorDeviceDataList);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void ShowSensorChartData(int sensorType ,List<SensorDeviceData> sensorDeviceDataList)
        {
            try
            {
                ChartValues<DateTimePoint> chartValues1 = new ChartValues<DateTimePoint>();
                ChartValues<DateTimePoint> chartValues2 = new ChartValues<DateTimePoint>();
                ChartValues<DateTimePoint> chartValues3 = new ChartValues<DateTimePoint>();
                for (int index = 0; index < sensorDeviceDataList.Count; index++)
                {
                    SensorDeviceData sensorDeviceData = sensorDeviceDataList[index];
                    if (sensorDeviceData != null)
                    {
                        chartValues1.Add(new DateTimePoint(sensorDeviceData.collect_time, sensorDeviceData.count_value1));
                        if (sensorDeviceData.sensor_type == 3)
                        {
                            chartValues2.Add(new DateTimePoint(sensorDeviceData.collect_time, sensorDeviceData.count_value2));
                            chartValues3.Add(new DateTimePoint(sensorDeviceData.collect_time, sensorDeviceData.count_value3));
                        }
                    }
                }
                if(sensorType == 3)
                {
                    InitChartConfig(chartValues1, chartValues2, chartValues3);
                }
                else
                {
                    InitChartConfig(chartValues1);
                }
                
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void InitChartConfig()
        {
            string title = "值";
            try
            {
                if (OscChart.InvokeRequired)
                {
                    OscChart.Invoke(new System.Action(() =>
                    {
                        OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                        {
                            Title = title,
                            PointGeometry = DefaultGeometries.Circle,
                            PointGeometrySize = 15,
                            StrokeThickness = 4,
                            LineSmoothness = 0,
                            PointForeground = System.Windows.Media.Brushes.Blue,
                            Values = InitChartValuesEmptyData(),
                            ScalesYAt = 0
                        });
                        OscChart.AxisX.Add(new LiveCharts.Wpf.Axis
                        {
                            //Title = "时间",
                            FontSize = 12,
                            DisableAnimations = true,
                            Foreground = System.Windows.Media.Brushes.Black,
                            //LabelFormatter = value => value.ToString(),
                            //LabelFormatter = value => new System.DateTime(System.DateTime.Now.Ticks - (long)(this.xTimes - (long)value) * this.intervalTime * 10000).ToString("mm:ss"),
                            // 设置X轴为DateTime类型
                            LabelFormatter = value => (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)value).ToLocalTime()).ToString("HH:mm:ss"),
                            //Separator = new Separator
                            //{
                            //    Step = 10,
                            //    IsEnabled = true
                            //},
                            //MaxValue = this.xCount,
                            //MinValue = 0
                        });
                        OscChart.AxisY.Add(new LiveCharts.Wpf.Axis
                        {
                            //Title = title,
                            FontSize = 12,
                            Foreground = System.Windows.Media.Brushes.White,
                            Position = AxisPosition.LeftBottom
                        });
                    }));
                }
                else
                {
                    OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                    {
                        Title = title,
                        PointGeometry = DefaultGeometries.Circle,
                        PointGeometrySize = 15,
                        StrokeThickness = 4,
                        LineSmoothness = 0,
                        PointForeground = System.Windows.Media.Brushes.Blue,
                        Values = InitChartValuesEmptyData(),
                        ScalesYAt = 0
                    });
                    OscChart.AxisX.Add(new LiveCharts.Wpf.Axis
                    {
                        //Title = "时间",
                        FontSize = 12,
                        DisableAnimations = true,
                        Foreground = System.Windows.Media.Brushes.Black,
                        //LabelFormatter = value => value.ToString(),
                        //LabelFormatter = value => new System.DateTime(System.DateTime.Now.Ticks - (long)(this.xTimes - (long)value) * this.intervalTime * 10000).ToString("mm:ss"),
                        // 设置X轴为DateTime类型
                        //LabelFormatter = value => new DateTime((long)(value/1000)).ToString("HH:mm:ss"),
                        LabelFormatter = value => (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)value).ToLocalTime()).ToString("HH:mm:ss"),
                        //Separator = new Separator
                        //{
                        //    Step = 10,
                        //    IsEnabled = true
                        //},
                        //MaxValue = this.xCount,
                        //MinValue = 0
                    });
                    OscChart.AxisY.Add(new LiveCharts.Wpf.Axis
                    {
                        //Title = title,
                        FontSize = 12,
                        Foreground = System.Windows.Media.Brushes.White,
                        Position = AxisPosition.LeftBottom
                    });
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            finally
            {
            }
        }


        private void InitChartConfig(ChartValues<DateTimePoint> chartValues)
        {
            try
            {
                // 假设你在非UI线程上
                if (OscChart.InvokeRequired)
                {
                    OscChart.Invoke(new System.Action(() =>
                    {
                        OscChart.Series.Clear();
                        OscChart.AxisX.Clear();
                        OscChart.AxisY.Clear();
                    }));
                }
                else
                {
                    OscChart.Series.Clear();
                    OscChart.AxisX.Clear();
                    OscChart.AxisY.Clear();
                }
                string title = "值";
                // 假设你在非UI线程上
                if (OscChart.InvokeRequired)
                {
                    OscChart.Invoke(new Action(() =>
                    {
                        OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                        {
                            Title = title,
                            PointGeometry = DefaultGeometries.Circle,
                            PointGeometrySize = 15,
                            StrokeThickness = 4,
                            LineSmoothness = 0,
                            PointForeground = System.Windows.Media.Brushes.Blue,
                            //Foreground = System.Windows.Media.Brushes.Black,
                            //FontSize = 20,
                            Values = chartValues,
                            ScalesYAt = 0
                        });
                        OscChart.AxisX.Add(new LiveCharts.Wpf.Axis
                        {
                            //Title = "时间",
                            FontSize = 12,
                            DisableAnimations = true,
                            Foreground = System.Windows.Media.Brushes.Black,
                            //LabelFormatter = value => value.ToString(),
                            //LabelFormatter = value => new System.DateTime(System.DateTime.Now.Ticks - (long)(this.xTimes - (long)value) * this.intervalTime * 10000).ToString("mm:ss"),
                            // 设置X轴为DateTime类型
                            //LabelFormatter = value => new DateTime((long)(value/1000)).ToString("HH:mm:ss"),
                            LabelFormatter = value => (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)value).ToLocalTime()).ToString("HH:mm:ss"),
                            //Separator = new Separator
                            //{
                            //    Step = 1,
                            //    IsEnabled = true
                            //},
                            //MaxValue = this.xCount,
                            //MinValue = 0
                        });
                        OscChart.AxisY.Add(new LiveCharts.Wpf.Axis
                        {
                            //Title = title,
                            FontSize = 12,
                            Foreground = System.Windows.Media.Brushes.White,
                            Position = AxisPosition.LeftBottom
                        });
                    }));
                }
                else
                {
                    OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                    {
                        Title = title,
                        PointGeometry = DefaultGeometries.Circle,
                        PointGeometrySize = 15,
                        StrokeThickness = 4,
                        LineSmoothness = 0,
                        PointForeground = System.Windows.Media.Brushes.Blue,
                        //Foreground = System.Windows.Media.Brushes.Black,
                        //FontSize = 20,
                        Values = chartValues,
                        ScalesYAt = 0
                    });
                    OscChart.AxisX.Add(new LiveCharts.Wpf.Axis
                    {
                        //Title = "时间",
                        FontSize = 12,
                        DisableAnimations = true,
                        Foreground = System.Windows.Media.Brushes.Black,
                        //LabelFormatter = value => value.ToString(),
                        //LabelFormatter = value => new System.DateTime(System.DateTime.Now.Ticks - (long)(this.xTimes - (long)value) * this.intervalTime * 10000).ToString("mm:ss"),
                        // 设置X轴为DateTime类型
                        //LabelFormatter = value => new DateTime((long)(value/1000)).ToString("HH:mm:ss"),
                        LabelFormatter = value => (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)value).ToLocalTime()).ToString("HH:mm:ss"),
                        //Separator = new Separator
                        //{
                        //    Step = 1,
                        //    IsEnabled = true
                        //},
                        //MaxValue = this.xCount,
                        //MinValue = 0
                    });
                    OscChart.AxisY.Add(new LiveCharts.Wpf.Axis
                    {
                        //Title = title,
                        FontSize = 12,
                        Foreground = System.Windows.Media.Brushes.White,
                        Position = AxisPosition.LeftBottom
                    });
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void InitChartConfig(ChartValues<DateTimePoint> chartValues1, ChartValues<DateTimePoint> chartValues2, ChartValues<DateTimePoint> chartValues3)
        {
            try
            {
                // 假设你在非UI线程上
                if (OscChart.InvokeRequired)
                {
                    OscChart.Invoke(new System.Action(() =>
                    {
                        OscChart.Series.Clear();
                        OscChart.AxisX.Clear();
                        OscChart.AxisY.Clear();
                    }));
                }
                else
                {
                    OscChart.Series.Clear();
                    OscChart.AxisX.Clear();
                    OscChart.AxisY.Clear();
                }
                string title = "值";
                // 假设你在非UI线程上
                if (OscChart.InvokeRequired)
                {
                    OscChart.Invoke(new Action(() =>
                    {
                        OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                        {
                            Title = title,
                            PointGeometry = DefaultGeometries.Circle,
                            PointGeometrySize = 15,
                            StrokeThickness = 4,
                            LineSmoothness = 0,
                            PointForeground = System.Windows.Media.Brushes.Blue,
                            //Foreground = System.Windows.Media.Brushes.Black,
                            //FontSize = 20,
                            Values = chartValues1,
                            ScalesYAt = 0
                        });
                        OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                        {
                            Title = title,
                            PointGeometry = DefaultGeometries.Circle,
                            PointGeometrySize = 15,
                            StrokeThickness = 4,
                            LineSmoothness = 0,
                            PointForeground = System.Windows.Media.Brushes.Blue,
                            //Foreground = System.Windows.Media.Brushes.Black,
                            //FontSize = 20,
                            Values = chartValues2,
                            ScalesYAt = 0
                        });
                        OscChart.Series.Add(new LiveCharts.Wpf.LineSeries
                        {
                            Title = title,
                            PointGeometry = DefaultGeometries.Circle,
                            PointGeometrySize = 15,
                            StrokeThickness = 4,
                            LineSmoothness = 0,
                            PointForeground = System.Windows.Media.Brushes.Blue,
                            //Foreground = System.Windows.Media.Brushes.Black,
                            //FontSize = 20,
                            Values = chartValues3,
                            ScalesYAt = 0
                        });
                        OscChart.AxisX.Add(new LiveCharts.Wpf.Axis
                        {
                            //Title = "时间",
                            FontSize = 12,
                            DisableAnimations = true,
                            Foreground = System.Windows.Media.Brushes.Black,
                            //LabelFormatter = value => value.ToString(),
                            //LabelFormatter = value => new System.DateTime(System.DateTime.Now.Ticks - (long)(this.xTimes - (long)value) * this.intervalTime * 10000).ToString("mm:ss"),
                            // 设置X轴为DateTime类型
                            //LabelFormatter = value => new DateTime((long)(value/1000)).ToString("HH:mm:ss"),
                            LabelFormatter = value => (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)value).ToLocalTime()).ToString("HH:mm:ss"),
                            //Unit = TimeSpan.FromMinutes(1).Ticks,
                            //Separator = new Separator
                            //{
                            //    Step = 1,
                            //    IsEnabled = true
                            //},
                            //MaxValue = this.xCount,
                            //MinValue = 0
                        });
                        OscChart.AxisY.Add(new LiveCharts.Wpf.Axis
                        {
                            //Title = title,
                            FontSize = 12,
                            Foreground = System.Windows.Media.Brushes.DodgerBlue,
                            Position = AxisPosition.LeftBottom
                        });
                    }));
                }
                else
                {
                    OscChart.Series.Add(new LiveCharts.Wpf.StackedAreaSeries
                    {
                        Title = title,
                        PointGeometry = DefaultGeometries.Circle,
                        PointGeometrySize = 15,
                        StrokeThickness = 4,
                        LineSmoothness = 1,
                        PointForeground = System.Windows.Media.Brushes.Blue,
                        //Foreground = System.Windows.Media.Brushes.Black,
                        //FontSize = 20,
                        Values = chartValues1,
                        ScalesYAt = 0
                    });
                    OscChart.Series.Add(new LiveCharts.Wpf.StackedAreaSeries
                    {
                        Title = title,
                        PointGeometry = DefaultGeometries.Circle,
                        PointGeometrySize = 15,
                        StrokeThickness = 4,
                        LineSmoothness = 1,
                        PointForeground = System.Windows.Media.Brushes.Blue,
                        //Foreground = System.Windows.Media.Brushes.Black,
                        //FontSize = 20,
                        Values = chartValues2,
                        ScalesYAt = 0
                    });
                    OscChart.Series.Add(new LiveCharts.Wpf.StackedAreaSeries
                    {
                        Title = title,
                        PointGeometry = DefaultGeometries.Circle,
                        PointGeometrySize = 15,
                        StrokeThickness = 4,
                        LineSmoothness = 1,
                        PointForeground = System.Windows.Media.Brushes.Blue,
                        //Foreground = System.Windows.Media.Brushes.Black,
                        //FontSize = 20,
                        Values = chartValues3,
                        ScalesYAt = 0
                    });
                    OscChart.AxisX.Add(new LiveCharts.Wpf.Axis
                    {
                        //Title = "时间",
                        FontSize = 12,
                        DisableAnimations = true,
                        Foreground = System.Windows.Media.Brushes.Black,
                        //LabelFormatter = value => value.ToString(),
                        //LabelFormatter = value => new System.DateTime(System.DateTime.Now.Ticks - (long)(this.xTimes - (long)value) * this.intervalTime * 10000).ToString("mm:ss"),
                        // 设置X轴为DateTime类型
                        //LabelFormatter = value => new DateTime((long)(value/1000)).ToString("HH:mm:ss"),
                        LabelFormatter = value => (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)value).ToLocalTime()).ToString("HH:mm:ss"),
                        //Unit = TimeSpan.FromMinutes(1).Ticks,
                        //Separator = new Separator
                        //{
                        //    Step = 1,
                        //    IsEnabled = true
                        //},
                        //MaxValue = this.xCount,
                        //MinValue = 0
                    });
                    OscChart.AxisY.Add(new LiveCharts.Wpf.Axis
                    {
                        //Title = title,
                        FontSize = 12,
                        Foreground = System.Windows.Media.Brushes.DodgerBlue,
                        Position = AxisPosition.LeftBottom
                    });
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }


        private void btnExport_Click(object sender, EventArgs e)
        {
            // 创建Excel应用程序实例
            this.excelApp = new Excel.Application();
            if (this.excelApp == null)
            {
                MessageBox.Show("无法创建excel对象，请确认excel环境是否正常");
                return;

            }
            this.excelApp.Visible = false;
            this.excelApp.UserControl = true;
            this.excelApp.DisplayAlerts = false;

            DateTime dt = DateTime.Today; // 获取今天的日期
            //DateTime yesterday = dt.AddDays(-1); // 获取前一天的日期
            string date = dt.Year.ToString("D4") + dt.Month.ToString("D2") + dt.Day.ToString("D2") + dt.Hour.ToString("D2") + dt.Minute.ToString("D2") + dt.Second.ToString("D2");
            Excel.Workbooks workbooks = this.excelApp.Workbooks;
            string filePath;
            if (this.waveFilePath == "")
            {
                filePath = AppDomain.CurrentDomain.BaseDirectory + this.waveFileName + @"-" + date + @".xlsx";
            }
            else
            {
                filePath = this.waveFilePath + this.waveFileName + @"-" + date + @".xlsx";
            }
            try
            {
                if (File.Exists(filePath))
                {
                    this.workbook = workbooks.Add(filePath); //加载模板
                }
                else
                {
                    File.Copy(AppDomain.CurrentDomain.BaseDirectory + this.waveFileName + @".xlsx", filePath, true);
                    this.workbook = workbooks.Add(filePath); //加载模板
                }
            }
            catch (Exception ex)
            {
                bool isUnlocked = FileUnlocker.UnlockFile(filePath);
                if (isUnlocked)
                {
                    this.workbook = workbooks.Add(filePath); //加载模板
                }
                else
                {
                    MessageBox.Show("存储 Excel 文件时出错,文件可能正被打开！\n" + ex.Message);
                    log.Error(ex.Message);
                    return;
                }
            }
            if (this.workbook == null)
            {
                MessageBox.Show("无法打开 Workbook 对象，请确认 Excel 文件是否正常");
                return;
            }

            if (!this.waveFileNameDate.Equals(date))
            {
                this.waveFileNameDate = date;
            }

            Excel.Sheets sheets = workbook.Sheets;
            Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); //第一个工作薄。
            if (worksheet == null)
            {
                MessageBox.Show("无法打开 Worksheet 对象，请确认 Excel 文件是否正常");
                return; //工作薄中没有工作表.
            }
            worksheet.Name = date;

            int columnIndex = 1; // A列的索引是1
            int columnCount = 0;

            //if ((resultList != null) && (resultList.Count > 0)){
            //    //写入数值
            //    for (int i = 0; i < resultList.Count; i++)
            //    {
            //        ResultSensorEntity resultSensorEntity = resultList.Get(i);
            //        //写入标题
            //        worksheet.Cells[columnCount + 1, 1] = resultSensorEntity.collect_time.ToString() + ":" + resultSensorEntity.channel_id.ToString() + ":" + resultSensorEntity.raster_type.ToString() + ":" + resultSensorEntity.raster_count.ToString()
            //             + ":" + resultSensorEntity.wave_length1.ToString() + ":" + resultSensorEntity.wave_length2.ToString() + ":" + resultSensorEntity.wave_length3.ToString() + ":" + resultSensorEntity.wave_length4.ToString()
            //             + ":" + resultSensorEntity.wave_length5.ToString() + ":" + resultSensorEntity.wave_length6.ToString() + ":" + resultSensorEntity.wave_length7.ToString() + ":" + resultSensorEntity.wave_length8.ToString()
            //             + ":" + resultSensorEntity.wave_length9.ToString() + ":" + resultSensorEntity.wave_length10.ToString() + ":" + resultSensorEntity.wave_length11.ToString() + ":" + resultSensorEntity.wave_length12.ToString()
            //             + ":" + resultSensorEntity.wave_length13.ToString() + ":" + resultSensorEntity.wave_length14.ToString() + ":" + resultSensorEntity.wave_length15.ToString() + ":" + resultSensorEntity.wave_length16.ToString()
            //             + ":" + resultSensorEntity.count_value1.ToString() + ":" + resultSensorEntity.count_value2.ToString() + ":" + resultSensorEntity.count_value3.ToString() + ":" + resultSensorEntity.count_value4.ToString()
            //             + ":" + resultSensorEntity.count_value5.ToString() + ":" + resultSensorEntity.count_value6.ToString() + ":" + resultSensorEntity.count_value7.ToString() + ":" + resultSensorEntity.count_value8.ToString()
            //             + ":" + resultSensorEntity.count_value9.ToString() + ":" + resultSensorEntity.count_value10.ToString() + ":" + resultSensorEntity.count_value11.ToString() + ":" + resultSensorEntity.count_value12.ToString()
            //             + ":" + resultSensorEntity.count_value13.ToString() + ":" + resultSensorEntity.count_value14.ToString() + ":" + resultSensorEntity.count_value15.ToString() + ":" + resultSensorEntity.count_value16.ToString();
            //        worksheet.Cells[columnCount + 1, i + 2] = resultSensorEntity.ToArrayString();
            //    }
            //}

            //if ((normalList != null) && (normalList.Count > 0))
            //{
            //    //写入数值
            //    for (int i = 0; i < normalList.Count; i++)
            //    {
            //        NormalSensorEntity normalSensorEntity = normalList.Get(i);
            //        //写入标题
            //        worksheet.Cells[columnCount + 1, 1] = "id:collect_time:channel_id:raster_count:wave_length1:wave_length2:wave_length3:wave_length4:wave_length5:wave_length6:wave_length7:wave_length8"
            //             + ":wave_length9:wave_length10:wave_length11:wave_length12:wave_length13:wave_length14:wave_length15:wave_length16";
            //        worksheet.Cells[columnCount + 1, i + 2] = normalSensorEntity.ToArrayString();
            //    }
            //}

            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            try
            {
                this.workbook.Saved = true;
                this.workbook.SaveAs(filePath);
            }
            catch (Exception ex)
            {
                bool isUnlocked = FileUnlocker.UnlockFile(filePath);
                if (isUnlocked)
                {
                    this.workbook.SaveAs(filePath);
                }
                else
                {
                    MessageBox.Show("存储 Excel 文件时出错,文件可能正被打开！\n" + ex.Message);
                    log.Error(ex.Message);
                    return;
                }
            }
        }

        public static long ToUnixTimestamp(DateTime dateTime)
        {
            return (long)Math.Floor((dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
        }

        public static long ToUnixTimestampMilliseconds(DateTime dateTime)
        {
            return (long)(dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }

        public class SensorDeviceData
        {
            public long id { get; set; }
            //采集时间
            public long collect_time { get; set; }
            //通道ID
            public int channel_id { get; set; }
            //传感器类型
            public int sensor_type { get; set; }
            //传感器数量
            public int sensor_count { get; set; }
            //传感器索引
            public int sensor_index { get; set; }
            //传感器ID
            public int sensor_id { get; set; }
            //传感器名称
            public string sensor_name { get; set; }
            //结果1
            public double count_value1 { get; set; }
            //结果2
            public double count_value2 { get; set; }
            //结果3
            public double count_value3 { get; set; }

            public override string ToString()
            {
                return id + ", " + collect_time + ", " + channel_id + ", " + sensor_type + ", " + sensor_count + ", " + sensor_index + ", " + sensor_id + ", " + sensor_name
                    + ", " + count_value1 + ", " + count_value2 + ", " + count_value3;
            }

            public string[] ToArrayString()
            {
                string[] data = new String[]{
                                id.ToString(),collect_time.ToString(),channel_id.ToString(),sensor_type.ToString(),sensor_count.ToString(),sensor_index.Message,sensor_id.ToString(),sensor_id.ToString(),
                                count_value1.ToString(),count_value2.ToString(),count_value3.ToString()};
                return data;
            }
        }
    }
}